#! /usr/bin/env python
# -*- coding: utf-8 -*-


# Copyright 2009 Larry Resnik, Lasfraka-Elixir

#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.

#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.

#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.


import os
import sys
from engine.sound_handler.audiere_handler import BGMPlayer

# These are for developers, not game players.
startup_options = {
    'pychecker':False,
    'profile':False,
    'psyco':True
}

if startup_options['pychecker']:
    os.environ['PYCHECKER'] = '-q'
    import pychecker.checker
if startup_options['profile']:
    import cProfile as profile
    import pstats
if startup_options['psyco']:
    try:
        import psyco
        psyco.profile()
        #psyco.log('psycolog', 'w', 10)
    except ImportError:
        pass

def string_convert_smart(str):
    """Returns a string as the same string, a Boolean, or a number."""
    if str.lower() == 'true':
        return True
    elif str.lower() == 'false':
        return False
    elif str.isdigit():
        if '.' in str:
            return float(str)
        else:
            return int(str)
    else:
        return str

def scrutinize_argv(args):
    """Acts upon the passed commands on the command line.

    This lets non-developers get at pyglet's options. The pyglet options
    are sent as "pyglet_XXXX [setting]" pairs. Invalid pyglet options are
    ignored. Settings that are numbers become numbers and settings that are
    Booleans become Booleans.

    Examples:
        python megamarix.py pyglet_shadow_window False
        python megamarix.py pyglet_graphics_vbo False pyglet_audio silent
    """

    # At the time of this writing, using pyglet 1.1.3, there is an issue with
    # importing any of pyglet's OpenGL things before disabling certain pyglet
    # options. Only people with a bad video driver may encounter it.
    # See http://groups.google.com/group/pyglet-users/web/faq under the
    # "Unable to share contexts" related topic.

    # Check every other item beginning with the 2nd item.
    for arg_index in range(1, len(sys.argv), 2):
        try:
            if sys.argv[arg_index].startswith('pyglet_') and \
                sys.argv[arg_index][7:] in pyglet.options:
                pyglet.options[sys.argv[arg_index][7:]] = \
                    string_convert_smart(sys.argv[arg_index + 1])
        except IndexError:
            # Maybe a parameter to set was passed, but no variable followed.
            pass

import pyglet
scrutinize_argv(sys.argv)
from engine import main

def set_to_true_path():
    """Get the path to this file and put it in the Python Path.

    The file path is acquired because the working directory of the file is the
    thing used in relative file loading.
    If the file is already on the Python Path, nothing happens.

    :rtype: string
    :return: The path to this file.
    """

    if hasattr(sys, 'frozen'):
        # This is the result of a py2exe'd program. __file__ does not exist,
        # so what will be used is the location of the Python DLL.
        trueDir = sys.executable
    else:
        trueDir = __file__
    truePath = os.path.abspath(os.path.dirname(trueDir))
    # Now put our path in the list of paths Python looks for our stuff in.
    if truePath not in sys.path:
        sys.path.insert(0, truePath)
    return truePath

filePath = set_to_true_path()

if startup_options['pychecker']:
    sys.exit()

bgm_player = BGMPlayer()
# By being set as a daemon thread, this thread dies when the parent dies.
bgm_player.daemon = True
bgm_player.start()
try:
    if startup_options['profile']:
        profile.run(
            'main.run_game(bgm_player, filePath, framerate=60.0)',
            'runstats')
        runStats = pstats.Stats('runstats')
        runstats.strip_dirs().sort_stats('cumulative').print_stats()
    else:
        main.run_game(bgm_player, filePath, framerate=60.0)
except KeyboardInterrupt:
    pass
except:
    # Some error was thrown. We'll put the error into a text file.
    try:
        import traceback
        import codecs
        print(u'An error occured. See error_log.txt for the traceback.')
        errorLog = open('error_log.txt', 'wb')
        # Give text editors a helping hand; tell them it is UTF-8.
        errorLog.write(codecs.BOM_UTF8)
        traceback.print_exc(file=errorLog)
        errorLog.close()
    except IOError:
        pass
bgm_player.kill()
# Join the thread to the parent thread so that it dies in unison.
bgm_player.join()
